<template>
  <div class="setting-data-cmp-box">
    <div class="form-info">
      
      <el-form label-position="top" ref="ruleForm" :model="dataInfo" :rules="rules">
        
        <!-- <div class="company-card-form-item company-card-form-item-name">
          <div class="form-label">
            门户名称
          </div>
          <el-form-item prop="name">
            <el-input
              v-model="dataInfo.name"
              :autofocus="false"
              placeholder="请输入"
              maxlength="20"
              :disabled="disabled"
            ></el-input>
            <el-button type="primary" @click="submitSet">
              保存
            </el-button>
          </el-form-item>
        </div> -->
        
      </el-form>
      
      <div class="setting-company-info">
        
        <div class="setting-company-info-row setting-company-info-row-header">
          <div class="setting-company-info-item">
            <div class="setting-company-info-item-label">
              {{$t('common.base.companyName2')}}
            </div>
            <div class="setting-company-info-item-content">
              {{ tenantData.tenantName }}
            </div>
          </div>
          
          <div class="setting-company-info-item">
            <div class="setting-company-info-item-label">
              {{$t('portal.phone')}}
            </div>
            <div class="setting-company-info-item-content">
              {{ tenantData.cellPhone }}
            </div>
          </div>
        </div>
        
        <div class="setting-company-info-row setting-company-info-row-address">
          <div class="setting-company-info-item">
            <div class="setting-company-info-item-label">
              {{$t('portal.address')}}
            </div>
            <div class="setting-company-info-item-content">
              {{ companyInfo.basicCompanyAddress || '' }}
            </div>
          </div>
        </div>
        
        <div class="setting-company-info-row">
          <div class="setting-company-info-item">
            <div class="setting-company-info-item-label">
              {{$t('product.qrcodeSetting.phoneContent.text6')}}
            </div>
            <div class="setting-company-info-item-content" ref="CompanyInfoElement">
              {{ companyInfo.basicCompanyInfo || '' }}
            </div>
            <div v-show=showToggleBasicCompanyInfo class="setting-company-info-item-content" :class="basicCompanyInfoClassNames">
              {{ companyInfo.basicCompanyInfo || '' }}
            </div>
          </div>
        </div>
        
        <div class="setting-company-info-row setting-company-info-row-button" v-if="isToggleBasicCompanyInfo">
          <div class="setting-company-info-item">
            <div class="setting-company-info-item-label">
            </div>
            <div class="setting-company-info-item-content">
              <span class="el-dropdown-link cur-point" @click="toggleCompanyInfo">
                {{ showToggleBasicCompanyInfo ? $t('common.base.collapse') : $t('task.components.taskAllotModal.expandMore') }}
                <i class="iconfont icon-fdn-select" :class="toggleBasicCompanyInfo ? 'is-reverse' : ''"></i>
              </span>
            </div>
          </div>
        </div>
        
        <div class="setting-company-info-footer">
          <i class="iconfont icon-fdn-info"></i>
          <span>
            {{$t('portal.setting.companyCardData.linkText1')}}
          </span>
          <span class="link-text setting-company-info-footer-link" @click="jumpCompanyTab">
            {{$t('portal.setting.companyCardData.linkText2')}}
          </span>
        </div>
        
      </div>
      
    </div>
  </div>
</template>
<script>
import _ from 'lodash';
import Uploader from 'packages/BaseUpload/uploader';
import { getLocalesOssUrl } from '@src/util/assets'
const userImg = getLocalesOssUrl('/myShop/logo.png');
import lineClamp from '@src/util/dom/lineClamp'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform'
let reg_phone = /^([0-9](?=.*[~!@#$%^&*()_+`\-={}:";'<>?,.]).{0,19}|(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,.]).{0,19}|([0-9]).{1,19}|(1[345678]\d{9}))$/;

export default {
  name: 'company-card-data',
  props: {
    tenant: {
      type: Object,
      default: () => ({})
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    infoData: {
      type: Object,
      default: () => ({})
    }
  },
  inject: ['cancelInfoData', 'changeFullscreenLoading'],
  data() {
    let validatePhone = (rule, value, callback) => {
      if (!reg_phone.test(value)) {
        callback(new Error(this.$t('portal.setting.companyCardData.tipText2')));
      }
      callback();
    };
    return {
      userImg,
      fileArr: [],
      dataInfo: {
        name: '',
        mobile: '',
        address: '',
        logoUrl: '',
        companyName: '',
      },
      dataInforReturn: {
        name: '',
        mobile: '',
        address: '',
        logoUrl: '',
        companyName: '',
      },
      rules: {
        name: [
          { required: true, message: this.$t('portal.setting.companyCardData.tipText1'), trigger: 'change' },
          { max: 50, message: this.$t('common.base.tip.maxCharacterTip', {num: '50'}), trigger: 'change' },
        ],
        mobile: [
          {
            validator: validatePhone,
            message: this.$t('portal.setting.companyCardData.tipText2'),
            trigger: 'change',
          },
        ],
        address: [{ required: true, message: this.$t('portal.setting.companyCardData.tipText3'), trigger: 'change' }],
      },
      pending: false,
      imgCover: false,
      isToggleBasicCompanyInfo: false,
      toggleBasicCompanyInfo: false,
    };
  },
  computed: {
    tenantData() {
      return this.tenant || {}
    },
    companyInfo() {
      return this.tenantData.attribute || {}
    },
    basicCompanyInfo() {
      return this.companyInfo.basicCompanyInfo
    },
    basicCompanyInfoClassNames() {
      return {
        'company-info-hidden': this.hiddenToggleBasicCompanyInfo,
        'company-info-block': this.showToggleBasicCompanyInfo,
      }
    },
    showToggleBasicCompanyInfo() {
      return this.isToggleBasicCompanyInfo && this.toggleBasicCompanyInfo
    },
    hiddenToggleBasicCompanyInfo() {
      return this.isToggleBasicCompanyInfo && !this.toggleBasicCompanyInfo
    }
  },
  watch: {
    basicCompanyInfo: {
      handler(newValue) {
        this.setBasicCompanyInfoStyle()
      },
      immediate: true
    }
  },
  activated() {
    this.$set(this, 'dataInfo', _.cloneDeep(this.infoData));
    this.$set(this, 'dataInforReturn', _.cloneDeep(this.infoData));
    this.$nextTick(() => {
      this.$refs['ruleForm'].clearValidate();
    });
  },
  methods: {
    onBeforeUploadImage(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error(this.$t('portal.setting.companyCardData.text1'));
      }
      if (!isLt2M) {
        this.$message.error(this.$t('portal.setting.companyCardData.text2', {size1: '2MB'}));
      }
      this.fileArr.push(file.raw);
      return isJPG && isLt2M;
    },
    UploadImage(param) {
      this.pending = true
      
      Uploader.upload(param.file, '/files/upload')
        .then((result) => {
          if (result.status != 0) {
            this.$message({
              message: `${result.message}`,
              duration: 1500,
              type: 'error',
            });
            return;
          }
          
          let file = result.data;
          let item = {
            id: file.id,
            filename: file.fileName,
            // 如果后端返回url,必须使用。如果后端不返回，需要拼接
            url: file.ossUrl || file.url || `/files/get?fileId=${file.id}`,
            fileSize: file.fileSizeStr,
          };
          this.dataInfo.logoUrl = item.url;
        })
        .catch((err) => {
          console.warn(err);
        })
        .finally(() => {
          this.pending = false
        });
    },
    fileChange(file) {
      return
    },
    changeImgCover(e) {
      this.imgCover = e;
    },
    saveData() {
      return new Promise((resolve, reject) => {
        this.$refs['ruleForm'].validate((valid) => {
          if (!valid) return reject();
          this.dataInforReturn = _.cloneDeep(this.dataInfo);
          this.$emit('changeInfoData', {
            item: this.dataInforReturn,
          });
          this.$nextTick(() => {
            resolve();
          });
          this.cancelInfoData();
        });
      });
    },
    resetData() {
      this.$refs['ruleForm'].clearValidate();
      this.dataInfo = _.cloneDeep(this.dataInforReturn);
    },
    clear() {
      this.dataInfo.logoUrl = '';
      this.imgCover = false;
    },
    setBasicCompanyInfoStyle() {
      this.$nextTick(() => {
        this.isToggleBasicCompanyInfo = lineClamp(
          this.$refs.CompanyInfoElement, 
          2, 
          { ellipsis: '...' }
        )
      })
    },
    toggleCompanyInfo() {
      this.$refs.CompanyInfoElement.style.display = this.toggleBasicCompanyInfo ? 'block' : 'none';
      this.toggleBasicCompanyInfo = !this.toggleBasicCompanyInfo
    },
    jumpCompanyTab() {
      // this.$platform.openTab({
      //   id: 'ACCOUNT_COMPANY',
      //   title: '公司设置',
      //   url: '/foundation/account/company',
      //   reload: true,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageFeAccountCompany,
        reload: true,
      })
    },
    submitSet() {
      this.$parent.submitSet()
    }
  },
};
</script>
<style lang="scss">
.setting-data-cmp-box {
  width: 100%;
  .form-info {
    padding: 12px;
  }
  .form-label {
    margin-bottom: 8px;
    span {
      font-size: 12px;
      color: #999;
      margin-left: 8px;
    }
  }
  .img-cover {
    position: absolute;
    z-index: 99;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    top: 0;
    left: 0;
    background: rgba($color: #000000, $alpha: 0.5);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    .iconfont {
      font-size: 30px;
    }
  }
}
</style>

<style lang="scss">
// upload start
.el-upload--picture-card {
  width: 96px;
  height: 96px;
  line-height: 106px;
  border-radius: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 96px;
  height: 96px;
  line-height: 96px;
  border-radius: 50%;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: $color-primary;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 96px;
  height: 96px;
  line-height: 96px;
  border-radius: 50%;
  text-align: center;
}
.avatar {
  width: 94px;
  height: 94px;
  border-radius: 50%;
  display: block;
}
// upload end
</style>

<style lang="scss">
.company-card-form-item {
  display: flex;
  .form-label {
    display: flex;
    align-items: center;
    width: 100px;
  }
}

.setting-data-cmp-box {
  .el-upload  {
    position: relative;
    overflow: inherit !important;
    .el-button {
      position: absolute;
      right: -120px;
      top: 32px;
    }
  }
}

.company-card-form-item-logo {
  height: 114px;
}
</style>

<style lang="scss">
.setting-data {
  height: auto !important;
  width: 100% !important;
}
.setting-company-info {
  margin-top: 6px;
  padding: 16px;
  width: 100%;
  background-color: #fafafa;
  border-radius: 4px;
  display: flex;
  flex-flow: column;
}

.setting-company-info-row-header {
  display: flex;
  .setting-company-info-item {
    width: 50%;
  }
}

.setting-company-info-row {
    margin-bottom: 7px;
}

.setting-company-info-item {
  display: flex;
  .setting-company-info-item-label {
    width: 60px;
  }
  .setting-company-info-item-content {
    flex: 1;
    margin-left: 19px;
  }
}

.setting-company-info-row-button {
  color: #8C8C8C;
}

.setting-company-info-row-address {
  .setting-company-info-item-content {
    @include text-ellipsis;
  }
}

.setting-company-info-footer {
  display: flex;
  align-items: center;
  padding-top: 9px;
  color: #595959;
  i {
    margin-right: 4px;
  }
}

.company-card-form-item-name {
  .el-form-item__content {
    display: flex;
  }
  .el-button {
    margin-left: 12px;
  }
  .el-input {
    width: 328px;
  }
}
</style>